#include "menuitemedidialog.h"

MenuItemEditDialog::MenuItemEditDialog(QWidget *parent)
    : QDialog(parent)
    , m_menuManager(nullptr)
    , m_mainLayout(nullptr)
    , m_formWidget(nullptr)
    , m_formLayout(nullptr)
    , m_nameEdit(nullptr)
    , m_categoryEdit(nullptr)
    , m_priceEdit(nullptr)
    , m_stockEdit(nullptr)
    , m_descriptionEdit(nullptr)
    , m_imageWidget(nullptr)
    , m_imageLayout(nullptr)
    , m_imagePreview(nullptr)
    , m_imageButtonLayout(nullptr)
    , m_selectImageButton(nullptr)
    , m_clearImageButton(nullptr)
    , m_imagePathLabel(nullptr)
    , m_buttonLayout(nullptr)
    , m_buttonWidget(nullptr)
    , m_saveButton(nullptr)
    , m_cancelButton(nullptr)
    , m_isEditMode(false)
{
    setModal(true);
    setMinimumSize(450, 500);
    resize(500, 600);
    
    setupUI();
    applyStyles();
}

MenuItemEditDialog::~MenuItemEditDialog()
{
    // Qt会自动清理子对象
}

void MenuItemEditDialog::setMenuManager(MenuManager *manager)
{
    m_menuManager = manager;
}

void MenuItemEditDialog::setAddMode(const QStringList &categories)
{
    m_isEditMode = false;
    m_editingItemId.clear();
    m_categories = categories;
    
    setWindowTitle("添加菜品");
    clearForm();
    
    // 更新分类下拉框
    m_categoryEdit->clear();
    m_categoryEdit->addItems(m_categories);
}

void MenuItemEditDialog::setEditMode(const MenuItem &item, const QStringList &categories)
{
    m_isEditMode = true;
    m_editingItemId = item.id;
    m_categories = categories;
    
    setWindowTitle(QString("编辑菜品 - %1").arg(item.name));
    
    // 更新分类下拉框
    m_categoryEdit->clear();
    m_categoryEdit->addItems(m_categories);
    
    // 填充表单
    fillForm(item);
}

void MenuItemEditDialog::accept()
{
    if (!validateFormData()) {
        return;
    }
    
    MenuItem item = getMenuItemFromForm();
    MenuOperationResult result;
    
    bool isNewItem = !m_isEditMode;
    if (isNewItem) {
        result = m_menuManager->addMenuItem(item);
    } else {
        result = m_menuManager->updateMenuItem(item);
    }
    
    if (result == MenuOperationResult::SUCCESS) {
        emit menuItemSaved(item, isNewItem);
        QDialog::accept();
    } else {
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setWindowTitle("保存失败");
        msgBox.setText(MenuManager::getOperationResultMessage(result));
        msgBox.setStyleSheet(getMessageBoxStyleSheet());
        msgBox.exec();
    }
}

void MenuItemEditDialog::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(15);
    
    setupFormControls();
    setupImageControls();
    setupButtons();
}

void MenuItemEditDialog::setupFormControls()
{
    m_formWidget = new QWidget();
    m_formLayout = new QFormLayout(m_formWidget);
    m_formLayout->setSpacing(12);
    m_formLayout->setLabelAlignment(Qt::AlignRight);
    
    // 菜品名称
    m_nameEdit = new QLineEdit();
    m_nameEdit->setPlaceholderText("请输入菜品名称");
    m_formLayout->addRow("菜品名称:", m_nameEdit);
    
    // 菜品分类
    m_categoryEdit = new QComboBox();
    m_categoryEdit->setEditable(false);
    m_formLayout->addRow("菜品分类:", m_categoryEdit);
    
    // 价格
    m_priceEdit = new QDoubleSpinBox();
    m_priceEdit->setRange(0.01, 9999.99);
    m_priceEdit->setDecimals(2);
    m_priceEdit->setSuffix(" 元");
    m_formLayout->addRow("菜品价格:", m_priceEdit);
    
    // 库存
    m_stockEdit = new QSpinBox();
    m_stockEdit->setRange(0, 99999);
    m_stockEdit->setSuffix(" 份");
    m_formLayout->addRow("库存数量:", m_stockEdit);
    
    // 描述
    m_descriptionEdit = new QTextEdit();
    m_descriptionEdit->setMaximumHeight(80);
    m_descriptionEdit->setPlaceholderText("请输入菜品描述...");
    m_formLayout->addRow("菜品描述:", m_descriptionEdit);
    
    m_mainLayout->addWidget(m_formWidget);
}

void MenuItemEditDialog::setupImageControls()
{
    m_imageWidget = new QWidget();
    m_imageLayout = new QVBoxLayout(m_imageWidget);
    m_imageLayout->setContentsMargins(0, 0, 0, 0);
    m_imageLayout->setSpacing(8);
    
    // 标题
    QLabel *imageTitle = new QLabel("菜品图片");
    imageTitle->setStyleSheet("font-weight: bold; color: #2c3e50;");
    m_imageLayout->addWidget(imageTitle);
    
    // 图片预览
    m_imagePreview = new QLabel();
    m_imagePreview->setFixedSize(200, 150);
    m_imagePreview->setAlignment(Qt::AlignCenter);
    m_imagePreview->setScaledContents(true);
    m_imageLayout->addWidget(m_imagePreview, 0, Qt::AlignCenter);
    
    // 图片操作按钮
    m_imageButtonLayout = new QHBoxLayout();
    m_selectImageButton = new QPushButton("选择图片");
    m_clearImageButton = new QPushButton("清除图片");
    
    m_imageButtonLayout->addWidget(m_selectImageButton);
    m_imageButtonLayout->addWidget(m_clearImageButton);
    m_imageButtonLayout->addStretch();
    m_imageLayout->addLayout(m_imageButtonLayout);
    
    // 图片路径显示
    m_imagePathLabel = new QLabel("无图片");
    m_imagePathLabel->setStyleSheet("color: #6c757d; font-size: 11px;");
    m_imagePathLabel->setWordWrap(true);
    m_imageLayout->addWidget(m_imagePathLabel);
    
    // 初始化图片预览（在所有控件创建完成后）
    clearImagePreview();
    
    // 连接信号
    connect(m_selectImageButton, &QPushButton::clicked, this, &MenuItemEditDialog::onSelectImageClicked);
    connect(m_clearImageButton, &QPushButton::clicked, this, &MenuItemEditDialog::onClearImageClicked);
    
    m_mainLayout->addWidget(m_imageWidget);
}

void MenuItemEditDialog::setupButtons()
{
    m_buttonWidget = new QWidget();
    m_buttonLayout = new QHBoxLayout(m_buttonWidget);
    m_buttonLayout->setContentsMargins(0, 0, 0, 0);
    
    m_saveButton = new QPushButton("保存");
    m_saveButton->setObjectName("saveButton");
    m_cancelButton = new QPushButton("取消");
    
    m_buttonLayout->addStretch();
    m_buttonLayout->addWidget(m_saveButton);
    m_buttonLayout->addWidget(m_cancelButton);
    
    // 连接信号
    connect(m_saveButton, &QPushButton::clicked, this, &MenuItemEditDialog::accept);
    connect(m_cancelButton, &QPushButton::clicked, this, &QDialog::reject);
    
    m_mainLayout->addWidget(m_buttonWidget);
}

void MenuItemEditDialog::applyStyles()
{
    setStyleSheet(R"(
        MenuItemEditDialog {
            background-color: #f8f9fa;
        }
        
        QLineEdit, QComboBox, QSpinBox, QDoubleSpinBox {
            border: 2px solid #dee2e6;
            border-radius: 4px;
            padding: 8px 12px;
            background-color: white;
            font-size: 13px;
            min-height: 20px;
        }
        
        QLineEdit:focus, QComboBox:focus, QSpinBox:focus, QDoubleSpinBox:focus {
            border-color: #3498db;
        }
        
        QTextEdit {
            border: 2px solid #dee2e6;
            border-radius: 4px;
            padding: 8px;
            background-color: white;
            font-size: 13px;
        }
        
        QTextEdit:focus {
            border-color: #3498db;
        }
        
        QPushButton {
            background-color: #6c757d;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 13px;
            min-width: 80px;
        }
        
        QPushButton:hover {
            background-color: #5a6268;
        }
        
        QPushButton:pressed {
            background-color: #545b62;
        }
        
        QPushButton[objectName="saveButton"] {
            background-color: #28a745;
        }
        
        QPushButton[objectName="saveButton"]:hover {
            background-color: #218838;
        }
        
        QFormLayout QLabel {
            font-weight: bold;
            color: #495057;
            min-width: 100px;
        }
    )");
    
    // 图片按钮样式
    m_selectImageButton->setStyleSheet(
        "QPushButton { "
        "background-color: #17a2b8; "
        "color: white; "
        "border: none; "
        "padding: 8px 16px; "
        "border-radius: 4px; "
        "font-size: 12px; "
        "min-width: 80px; "
        "}"
        "QPushButton:hover { background-color: #138496; }"
    );
    
    m_clearImageButton->setStyleSheet(
        "QPushButton { "
        "background-color: #dc3545; "
        "color: white; "
        "border: none; "
        "padding: 8px 16px; "
        "border-radius: 4px; "
        "font-size: 12px; "
        "min-width: 80px; "
        "}"
        "QPushButton:hover { background-color: #c82333; }"
    );
}

void MenuItemEditDialog::clearForm()
{
    m_nameEdit->clear();
    m_categoryEdit->setCurrentIndex(-1);
    m_priceEdit->setValue(0.01);
    m_stockEdit->setValue(0);
    m_descriptionEdit->clear();
    clearImagePreview();
}

void MenuItemEditDialog::fillForm(const MenuItem &item)
{
    m_nameEdit->setText(item.name);
    m_categoryEdit->setCurrentText(item.category);
    m_priceEdit->setValue(item.price);
    m_stockEdit->setValue(item.stock);
    m_descriptionEdit->setPlainText(item.description);
    updateImagePreview(item.imageUrl);
}

MenuItem MenuItemEditDialog::getMenuItemFromForm()
{
    MenuItem item;
    item.id = m_editingItemId;
    item.name = m_nameEdit->text().trimmed();
    item.category = m_categoryEdit->currentText().trimmed();
    item.price = m_priceEdit->value();
    item.stock = m_stockEdit->value();
    item.description = m_descriptionEdit->toPlainText().trimmed();
    item.imageUrl = m_currentImagePath;
    
    if (item.id.isEmpty()) {
        // 新建菜品 - 使用智能ID生成
        if (m_menuManager) {
            QList<MenuItem> existingItems = m_menuManager->getAllMenuItems();
            item.id = m_menuManager->generateSmartMenuItemId(existingItems);
        } else {
            // 备用方案：使用旧的UUID生成方式
            item.id = MenuManager::generateMenuItemId();
        }
        item.createdDate = QDateTime::currentDateTime();
        item.salesCount = 0;
    } else {
        // 编辑现有菜品 - 保留原有的创建时间和销售数据
        if (m_menuManager) {
            MenuItem existingItem = m_menuManager->getMenuItemById(item.id);
            if (existingItem.isValid()) {
                item.createdDate = existingItem.createdDate;
                item.salesCount = existingItem.salesCount;
            } else {
                item.createdDate = QDateTime::currentDateTime();
                item.salesCount = 0;
            }
        } else {
            item.createdDate = QDateTime::currentDateTime();
            item.salesCount = 0;
        }
    }
    item.lastModified = QDateTime::currentDateTime();
    
    return item;
}

bool MenuItemEditDialog::validateFormData()
{
    if (m_nameEdit->text().trimmed().isEmpty()) {
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setWindowTitle("验证失败");
        msgBox.setText("菜品名称不能为空！");
        msgBox.setStyleSheet(getMessageBoxStyleSheet());
        msgBox.exec();
        m_nameEdit->setFocus();
        return false;
    }
    
    if (m_categoryEdit->currentText().trimmed().isEmpty()) {
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setWindowTitle("验证失败");
        msgBox.setText("请选择菜品分类！");
        msgBox.setStyleSheet(getMessageBoxStyleSheet());
        msgBox.exec();
        m_categoryEdit->setFocus();
        return false;
    }
    
    if (m_priceEdit->value() <= 0) {
        QMessageBox msgBox(this);
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setWindowTitle("验证失败");
        msgBox.setText("菜品价格必须大于0！");
        msgBox.setStyleSheet(getMessageBoxStyleSheet());
        msgBox.exec();
        m_priceEdit->setFocus();
        return false;
    }
    
    // 检查名称重复（排除当前编辑的项目）
    if (m_menuManager) {
        if (m_menuManager->isMenuItemNameDuplicate(m_nameEdit->text().trimmed(), m_editingItemId)) {
            QMessageBox msgBox(this);
            msgBox.setIcon(QMessageBox::Warning);
            msgBox.setWindowTitle("验证失败");
            msgBox.setText("菜品名称已存在！");
            msgBox.setStyleSheet(getMessageBoxStyleSheet());
            msgBox.exec();
            m_nameEdit->setFocus();
            return false;
        }
    }
    
    return true;
}

void MenuItemEditDialog::onSelectImageClicked()
{
    QString fileName = QFileDialog::getOpenFileName(
        this,
        "选择菜品图片",
        QDir::homePath(),
        "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif);;所有文件 (*)"
    );
    
    if (!fileName.isEmpty()) {
        // 获取菜品名称和分类用于文件命名
        QString itemName = m_nameEdit->text().trimmed();
        QString category = m_categoryEdit->currentText().trimmed();
        
        if (itemName.isEmpty()) {
            QMessageBox msgBox(this);
            msgBox.setIcon(QMessageBox::Information);
            msgBox.setWindowTitle("提示");
            msgBox.setText("请先填写菜品名称");
            msgBox.setStyleSheet(getMessageBoxStyleSheet());
            msgBox.exec();
            return;
        }
        
        if (category.isEmpty()) {
            QMessageBox msgBox(this);
            msgBox.setIcon(QMessageBox::Information);
            msgBox.setWindowTitle("提示");
            msgBox.setText("请先选择菜品分类");
            msgBox.setStyleSheet(getMessageBoxStyleSheet());
            msgBox.exec();
            return;
        }
        
        // 复制图片到资源目录
        QString destPath = copyImageToResourceDir(fileName, category, itemName);
        if (!destPath.isEmpty()) {
            updateImagePreview(destPath);
        } else {
            QMessageBox msgBox(this);
            msgBox.setIcon(QMessageBox::Critical);
            msgBox.setWindowTitle("错误");
            msgBox.setText("图片复制失败，请检查文件权限");
            msgBox.setStyleSheet(getMessageBoxStyleSheet());
            msgBox.exec();
        }
    }
}

void MenuItemEditDialog::onClearImageClicked()
{
    clearImagePreview();
}

void MenuItemEditDialog::updateImagePreview(const QString &imagePath)
{
    m_currentImagePath = imagePath;
    
    if (imagePath.isEmpty()) {
        clearImagePreview();
        return;
    }
    
    QPixmap pixmap(imagePath);
    if (!pixmap.isNull()) {
        QPixmap scaledPixmap = pixmap.scaled(200, 150, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        m_imagePreview->setPixmap(scaledPixmap);
        m_imagePreview->setStyleSheet(
            "QLabel { "
            "border: 2px solid #28a745; "
            "border-radius: 4px; "
            "background-color: #ffffff; "
            "}"
        );
        
        // 显示相对路径
        QString relativePath = imagePath;
        QString projectRoot = QDir::currentPath();
        if (imagePath.startsWith(projectRoot)) {
            relativePath = imagePath.mid(projectRoot.length() + 1);
        }
        m_imagePathLabel->setText(relativePath);
    } else {
        m_imagePreview->setText("图片加载失败");
        m_imagePreview->setStyleSheet(
            "QLabel { "
            "border: 2px dashed #dc3545; "
            "border-radius: 4px; "
            "background-color: #f8f9fa; "
            "color: #dc3545; "
            "}"
        );
        m_imagePathLabel->setText("图片路径无效: " + imagePath);
    }
}

void MenuItemEditDialog::clearImagePreview()
{
    m_currentImagePath = "";
    m_imagePreview->clear();
    m_imagePreview->setText("点击选择图片添加菜品图片");
    m_imagePreview->setStyleSheet(
        "QLabel { "
        "border: 2px dashed #6c757d; "
        "border-radius: 4px; "
        "background-color: #f8f9fa; "
        "color: #6c757d; "
        "}"
    );
    m_imagePathLabel->setText("无图片");
}

QString MenuItemEditDialog::copyImageToResourceDir(const QString &sourceImagePath, const QString &category, const QString &itemName)
{
    // 获取文件信息
    QFileInfo sourceInfo(sourceImagePath);
    if (!sourceInfo.exists() || !sourceInfo.isFile()) {
        return "";
    }
    
    // 构建目标目录
    QString projectRoot = QDir::currentPath();
    QString resourceDir = projectRoot + "/resources/images/menu_items";
    
    // 分类目录映射
    QMap<QString, QString> categoryMap;
    categoryMap["主食"] = "dishes";
    categoryMap["饮品"] = "drinks";
    categoryMap["小菜"] = "appetizers";
    categoryMap["汤品"] = "soups";
    categoryMap["甜品"] = "desserts";
    categoryMap["凉菜"] = "cold_dishes";
    categoryMap["热菜"] = "hot_dishes";
    
    QString categoryDir = categoryMap.value(category, "others");
    QString targetDir = resourceDir + "/" + categoryDir;
    
    // 确保目标目录存在
    QDir dir;
    if (!dir.mkpath(targetDir)) {
        return "";
    }
    
    // 构建目标文件名
    QString extension = sourceInfo.suffix().toLower();
    QString targetFileName = QString("%1_%2_200x150.%3")
                           .arg(categoryDir)
                           .arg(itemName)
                           .arg(extension);
    
    QString targetPath = targetDir + "/" + targetFileName;
    
    // 如果目标文件已存在，先删除
    if (QFile::exists(targetPath)) {
        QFile::remove(targetPath);
    }
    
    // 复制文件
    if (QFile::copy(sourceImagePath, targetPath)) {
        // 返回相对路径
        QString relativePath = targetPath.mid(projectRoot.length() + 1);
        return relativePath;
    }
    
    return "";
}

QString MenuItemEditDialog::getMessageBoxStyleSheet() const
{
    return R"(
        QMessageBox {
            background-color: #f5f5f5;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 13px;
        }
        
        QMessageBox QLabel {
            color: #2c3e50;
            font-size: 14px;
            margin: 10px;
            background-color: transparent;
        }
        
        QMessageBox QPushButton {
            background-color: #007bff;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            padding: 8px 20px;
            min-width: 80px;
            font-weight: bold;
            font-size: 13px;
        }
        
        QMessageBox QPushButton:hover {
            background-color: #0056b3;
        }
        
        QMessageBox QPushButton:pressed {
            background-color: #004085;
        }
    )";
}
